import { isSupportSticky } from '@/utils/css.js'
import WorkList from '@/components/performance/work_list/index.vue'
import Introduction from './introduction.vue'
import Evaluation from './evaluation.vue'
import Rules from './rules.vue'
import Calendar from '@/components/performance/vue-calendar/index.vue'
import { mapMutations, mapState } from 'vuex'
import defaultInitData from './initDefaultData.js'
import { getDateDiff, safarigetdate } from '@/utils/date.js'
import { id } from '@/utils/_.js'
import { getuserUid } from '@/utils/auth.js'
import { ImagePreview } from 'vant'

function ceiling(obj, cb) {
    var ot = obj.offsetTop;
    var box = obj.parentNode
    box.onscroll = function () {
        var st = box.scrollTop || box.scrollTop
        obj.style.position = st >= ot ? "fixed" : ""
        cb && cb()
    }
}
let overflowLoading = false
const handleOverflowView = ({ dom, gapNumber, cb }) => {
    let scrollHeight = dom.children[0].getBoundingClientRect().height
    let domHeight = window.parseInt(window.getComputedStyle(dom).height)
    if(scrollHeight - dom.scrollTop - gapNumber < domHeight){
        cb && cb()
    }
}
export default {
    components: {
        WorkList,
        Introduction,
        Evaluation,
        Rules,
        Calendar,
    },
    data: defaultInitData,
    computed: {
        ...mapState([
            'payOrderSelectDateFullDateArr',
            'payOrderDemandActive',
        ]),
        realPrice(v){
            console.log('this.payOrderDemandActive')
            console.log(this.payOrderDemandActive)
            let isAsyncModel = false
            try {
                // 全景图1.5倍。和某新讨论过了
                isAsyncModel = this.payOrderDemandActive.includes('360全景图')   
            } catch (error) {
                console.log(error)
            }
            let multiple = isAsyncModel ? 1.5 : 1
            return this.userInfo.ltTimePrice * multiple
        },
    },
    created() {
        let errorHandle = () => {
            console.log('参数错误')
            this.$toast('参数异常')
            this.$router.go(-1)
        }
        // let isAlert = this.$route.query?.isAlert
        let isAlert = false
        console.log('referer')
        console.log(this.$referer)
        // || !isAlert
        if(this.$referer.path === '/performance/pay_order'){
            this.showDemandList = false
            this.clickSelectDateAlert = false
        }
        // 表现师UID
        // let userUid = '834532c343a911e9855d6045cb8a6182'
        let userUid = this.$route.query?.buserid
        if(!userUid){
            errorHandle()
            return
        }
        this.userUid = userUid

        // 初始化 需求效果
        this.setSkillList()
        this.fullBaseData()
        this.initResumeDetailData({
            userUid: this.userUid
        })
        // TODO 待优化成展示得时候才执行
        this.initCommentData({
            pageNum: this.commentPageNum,
            pageSize: this.commentPageSize,
            userUid: this.userUid,
        })
        // 初始化订单详情
        // 初始化上门时间（H：M）
        this.UPDATE(['payOrderUpDoordateCelectIndex', 0])
        this.UPDATE(['payOrderUpDoorDateCelectActive', ''])
        // 项目名称初始化
        this.UPDATE(['payOrderProjectName', ''])
        // 需求效果初始化
        // this.UPDATE(['payOrderDemandIndex', 0])
        // this.UPDATE(['payOrderDemandActive', ''])
        // 支付方式初始化
        this.UPDATE(['payOrderPayWayActiveIndex', 0])
    },
    mounted() {
        let tabDom = this.$refs.tabSticky
        let UlDom = this.$refs.UlDom
        // 不兼容css3中的Sticky属性， 使用js动态修改
        if (!isSupportSticky()) {
            ceiling(tabDom)
        }
        // 每次到底部时  控制每个组件使用scroll分页
        let handleNextUseScroll = (cb) => () => {
            //  评价时使用
            switch (this.tabInfo.activeIndex) {
                case 0: {
                    break
                }
                case 1: {
                    break
                }
                case 2: {
                    if (overflowLoading)
                        break
                    overflowLoading = true
                    cb && cb(2)
                    break
                }
                case 3: {
                    break
                }
                default: {
                    console.log('tabInfo.activeIndex异常')
                }
            }
        }
        UlDom.onscroll =  () => {
            handleOverflowView({
                dom: UlDom,
                gapNumber: 10,
                cb: handleNextUseScroll((index) => {
                    // 数据处理
                    switch (index) {
                        case 2: {
                            console.log('评价 next')
                            if(this.commentLast){
                                return
                            }
                            overflowLoading = true
                            this.commentPageNum += 1
                            let params = {
                                ...this.commentParamsOld,
                                pageNum: this.commentPageNum,
                            }
                            this.initCommentData(params, () => {
                                overflowLoading = false
                            })
                            break
                        }
                    }
                })
            })
        }
    },
    methods: {
        clickDemandMask(){
            this.showDemandList = false
        },
        catheadimg(img){
            ImagePreview({
                images: [img], 
                showIndex: false,
                onClose: () => {}
            })
        },
        async setSkillList(){ 
            // TODO 加载中状态           
            let params = {
                bUserUid: this.userUid
            }
            let dataResponse
            try{
                dataResponse = await HTTP('app/buser/getSkillByBuserUid', params)
                if(dataResponse.code !== 200){
                    this.$toast(dataResponse.msg || '异常')
                    return
                }
                console.log('--技能标签--')
                console.log(dataResponse.data)
                // this.orightSkill = dataResponse.data.skillTargetsList
                let demandList = dataResponse.data
                this.demandList = demandList
                console.log(demandList)
            }catch(e){
                console.log(e)
                this.$toast('数据开小差了')
            }
        },
        xuanzhexuqiuxiaoguo(value, index){
            if(!value.flag){
                return
            }
            this.demandListChange = {
                value: value.name, uid: value.uid, index, run: true
            }
        },
        quxiuxiaoguoquedingxuanzhe(){
            if(!this.demandListChange.run){
                this.$toast('未选择需求效果哦')
                return
            }
            let {value, uid, index} = this.demandListChange
            this.UPDATE(['payOrderDemandActive', value])
            this.UPDATE(['payOrderDemandIndex', index])
            this.UPDATE(['payOrderDemandUid', uid])
            this.showDemandList = false
            this.clickSelectDateAlert = false
            this.selectDate()
        },
        ...mapMutations([
            'UPDATE'
        ]),
        invite(){
            this.$router.push('/designer/invite')
        },
        substr(v, len){
            if(!v){
                return ''
            }
            if(v.length > len){
                v = v.substr(0, len) + '...'
            }
            return v
        },
        async initResumeDetailData(params){
            let data = await HTTP('app/resume/resumeDetail', params)
            if(data.code !== 200){
                this.$toast(data.msg || '服务器异常')
                return
            }
            console.log('简历')
            console.log(data.data)
            this.introductionData = {
                ...data.data,
                resumeSkillInfos: data.data.resumeSkillInfos.map(e => ({
                    name: e.skillName || '数据异常',
                })),
                resumeTypesInfos: data.data.resumeTypesInfos.
                    flatMap(e => e.childs.map(e => ({ name: e.typeName || '数据异常' }))),
                resumeStylesInfos: data.data.resumeStylesInfos.map(e => ({
                    name: e.styleName || '数据异常',
                })),
            }
        },
        async star() {
            let addResponse
            let delResponse
            if (this.starRun) {
                this.$toast('正在修改中')
                return
            }
            // 锁
            this.starRun = true
            try {
                if (!this.isStar) {
                    addResponse = await HTTP('app/attentionOrBlacklist/insertAttentionOrBlacklist', {
                        type: 1,
                        attentionUserUid: this.userUid,
                        createBy: getuserUid()
                    })
                    // 锁 开
                    this.starRun = false
                    if (addResponse.code !== 200) {
                        this.$toast(addResponse.msg || '服务器异常')
                        return
                    }
                    this.isStar = true
                    if (this.userInfo.attention) {
                        this.userInfo.attention.uid = addResponse.data
                    } else {
                        this.userInfo.attention = {
                            uid: addResponse.data
                        }
                    }
                    // TODO 更新uid
                    this.$toast('关注成功')
                    console.log('--addResponse--')
                    console.log(addResponse)
                } else {
                    if (!this.userInfo.attention) {
                        this.$toast('异常')
                        return
                    }
                    let params = {
                        uid: this.userInfo.attention.uid
                    }
                    delResponse = await HTTP('app/attentionOrBlacklist/deleteAttentionOrBlacklistByUid', params)
                    // 锁 开
                    this.starRun = false
                    console.log(delResponse, params)
                    if (delResponse.code !== 200) {
                        this.$toast(delResponse.msg || '服务器异常')
                        return
                    }
                    this.isStar = false
                    this.$toast('取消关注成功')
                    console.log('--addResponse--')
                    console.log(addResponse)
                }
            } catch (e) {
                console.log(e)
                this.$toast('服务器异常')
            }
            // setTimeout(() => {
            //         this.isStar = !this.isStar
            //         this.starRun = false
            // }, 1e3)
        },
        switchOptions(index) {
            this.tabInfo.activeIndex = index
        },
        async fullBaseData() {
            this.workStatus = 1
            this.loadUserInfoStatus = 1
            let workListResponse
            let userInfoResponse
            try {
                workListResponse = await HTTP('app/image/getUserWorks', {
                    userUid: this.userUid,
                    months: 6,
                })
                
                // TEST
                // setTimeout(() => {
                //     // 执行订阅
                //     this.userBaseInfoToken.forEach(e => {
                //         e()
                //     })
                // }, 3e3)
                // return
                userInfoResponse = await HTTP('app/buser/getBUserOrdersCountDetail', {
                    // 表现师UID
                    bUserUid: this.userUid,
                    userUid: getuserUid(),
                })
                if (workListResponse.code !== 200) {
                    console.log('---异常1--')
                    this.$toast(workListResponse.msg || '数据开小差了')
                    return
                }
                if (userInfoResponse.code !== 200) {
                    console.log('---异常2--')
                    this.$toast(userInfoResponse.msg || '数据开小差了')
                    return
                }
                this.userInfo = userInfoResponse.data
                this.isStar = userInfoResponse.data.attention ? true : false
                this.workList = workListResponse.data ? workListResponse.data.map(e => {
                    return {
                        title: e.month,
                        imgs: e.list.map(e => {
                            return {src: e.shortImgUrl, imageUrl: e.imageUrl}
                        })
                    }
                })
                :[]
                // this.workList = workListResponse.data.list ? workListResponse.data.list
                //     .map(e => ({ ...e, title: e.createDate.split('-').splice(0, 2).join('-') }))
                //     .reduce((a, b) => {
                //         if (a.length !== 0 && a[a.length - 1].title === b.title) {
                //             a[a.length - 1].imgs.push({ src: b.shortImgUrl })
                //         } else {
                //             a.push({
                //                 title: b.title,
                //                 imgs: [{ src: b.shortImgUrl }]
                //             })
                //         }
                //         return a
                //     }, [])
                //     : []
                this.workStatus = 2
                this.loadUserInfoStatus = 2
                // 执行订阅
                this.userBaseInfoToken.forEach(e => {
                    e()
                })
                console.log('workListResponse')
                console.log(workListResponse)
                console.log('userInfoResponse')
                console.log(userInfoResponse)
            } catch (error) {
                console.log(error)
                this.$toast('数据开小差了')
            }
        },
        selectDate() {
            if(this.clickSelectDateAlert === true){
                this.showDemandList = true
                return
            }
            // 已加载过数据，直接展示
            if(this.selectDateLoad){
                this.isOpTimes = true
                return
            }
            const toast = this.$toast.loading({
                duration: 0,
                mask: true,
                message: '加载数据中...'
            })
            let success = () => {
                setTimeout(() => {
                    toast.clear()
                    this.isOpTimes = true
                    this.selectDateLoad = true  
                }, 50)
            }
            // 依赖的数据未加载完成，基本数据的后台接口崩了就无法得到金额的处理
            if(!this.userInfo.originalPrice){
                // 放入列队，等待数据加载完成，自动触发下一个接口
                // this.$toast('数据未加载完成，请稍后再试')
                toast.message = '数据未加载完成, 自动加载中...'
                let loadUserInfoCb = () => {
                    console.log('ok')
                    success()
                }
                // 加入订阅
                this.userBaseInfoToken.push(loadUserInfoCb)
                return
            }
            // 预约日期服务时间
            // TODO 当前接口挂了的处理
            this.initServeDate(success)
        },
        nextPage(selected) {
            this.isOpTimes = false
            console.log(selected)
            this.UPDATE(['payOrderConventionDate', selected])
            this.$router.push(`/performance/pay_order?price=${this.userInfo.ltTimePrice}&userUid=${this.userUid}`)
        },
        calendarClose() {
            this.isOpTimes = false
        },
        async initCommentData(params, successCb) {
            let response
            let mutationReply = row => {
                return {
                    name: row.createName,
                    inner: row.replyContent,
                    time: getDateDiff(+new Date(safarigetdate(row.createDate))),
                    imgs: [],
                }
            }
            let mutationRow = row => {
                return {
                    ...row,
                    img: row.createPictorUrl,
                    name: row.createrUserName,
                    // TODO 时间mutation IOS可能有问题
                    time: getDateDiff(+new Date(safarigetdate(row.createDate))),
                    evaluation: row.label || '',
                    inner: row.content,
                    imgs: row.reviewImgInfoList ? row.reviewImgInfoList.map(e => ({ src: e.imageUrl })) : [],
                    reviewInfos: row.reviewInfos ? row.reviewInfos.map(mutationRow) : null,
                    // revieweReplyInfo: row.revieweReplyInfo ? [mutationRow(row.revieweReplyInfo)] : null,
                    revieweReplyInfo: row.revieweReplyInfo ? row.revieweReplyInfo.filter(id).map(mutationReply) : null,
                }
            }
            try {
                response = await HTTP('app/buser/getBAssessInfo', params)
                if (response.code !== 200) {
                    this.$toast(response.msg || '服务器异常')
                    return
                }
                if(!response.data.userEfficiency || response.data.userEfficiency.length === 0) {
                    this.nocomment = true
                }else{
                    console.log('response.data')
                    console.log(response.data)
                    let list = response.data.reviewInfos.map(mutationRow)
                    // 1:效率2:服务3:沟通4:质量
                    for (let i = 0; i <= 3; i++) {
                        let score = response.data.userEfficiency.filter(e => e.assessType === i + 1)[0].score
                        this.commentGrades[i].n = score
                    }
                    // 总评分
                    this.commentScore = response.data.score
                    // 评论
                    this.commentList.push(...list)
                    this.commentParamsOld = params
                    successCb && successCb()
                    // TODO 应该是hi后台给字段。
                    if (list.length === 0) {
                        this.commentLast = true
                    }
                    console.log('list')
                    console.log(list)
                }
            } catch (e) {
                console.log(e)
                this.$toast('服务器异常')
            }
        },
        async initServeDate(cb){
            let params = {
                userUid: this.userUid,
                sUserUid: getuserUid()
            }
            let responseDate = await HTTP('app/orderSetting/getOrderServiceDate', params)
            let fullList = []
            if(responseDate.code !== 200){
                this.$toast(responseDate.msg || '服务器异常')
                return
            }
            // 满（没空）状态
            fullList = responseDate.data.dateList
            // 过滤有时间的表现师
            .filter(e => {
                // 没空并且被预约
                return (!e.todayStopOrder && e.isReservation) ? true : 
                    e.todayStopOrder ? true : 
                    false
            })
            .map(e => {
                return e.preordainDate.split('-').map(e => +e).join('/')
            })
            // .filter((e, i) => i < 8)
            this.UPDATE(['payOrderSelectDateFullDateArr', fullList])
            cb && cb()
            console.log('预约日期 时间')
            console.log(responseDate)
            console.log(fullList)
        },
        back(){
            this.$router.go(-1)
        }
    }
}